package com.jsnkj.basic.fragment

import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.jsnkj.basic.R
import com.jsnkj.basic.activity.DownActivity
import com.jsnkj.basic.activity.TextActivity
import com.jsnkj.basic.adapter.HomeAdapter
import com.jsnkj.basic.bean.HomeItemBean
import com.jsnkj.basic.config.SpConfig
import com.jsnkj.basic.databinding.FragmentHomeBinding
import com.jsnkj.basic.dialog.JoinPlayerDialog
import com.jsnkj.basic.mvvm.BaseMVVMActivity
import com.jsnkj.basic.mvvm.BaseMVVMFragment
import com.jsnkj.basic.util.ErrorResultUtil
import com.jsnkj.basic.util.MediaUtil
import com.jsnkj.basic.util.SharePreferencesUtil
import com.jsnkj.basic.util.jsonToString
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions


class HomeFragment : BaseMVVMFragment<FragmentHomeBinding, HomeViewModel>(), View.OnClickListener {

    companion object {
        fun newInstance() = HomeFragment()
    }

    override val layoutId: Int
        get() = R.layout.fragment_home

    private var homeAdapter: HomeAdapter? = null

    var joinPlayerDialog: JoinPlayerDialog? = null

    override fun initView(savedInstanceState: Bundle?) {
        mVDB.clickListener = this

        mVM.postHttpResult.observe(this) {
            homeAdapter =
                HomeAdapter(requireActivity(), it, object : HomeAdapter.onItemClickListener {
                    override fun onItemCallBack(bean: HomeItemBean, position: Int) {

                        com.jsnkj.basic.util.LogUtils.e("点击内容：${bean.toString()}")
                        if (bean.down_url.isNullOrEmpty()) {
                            com.jsnkj.basic.util.ToastUtils.show("下载地址为空，请联系服务人员")
                        } else {
                            XXPermissions.with(requireActivity()) // 申请单个权限
                                .permission(Permission.Group.STORAGE)// 申请多个权限
                                .request(object : OnPermissionCallback {
                                    override fun onGranted(
                                        permissions: List<String>,
                                        all: Boolean
                                    ) {
                                        if (all) {
                                            DownActivity.startDownActivity(
                                                requireActivity(),
                                                bean.jsonToString()
                                            )
                                        } else {
                                            com.jsnkj.basic.util.ToastUtils.show("获取部分权限成功，但部分权限未正常授予")
                                        }
                                    }

                                    override fun onDenied(
                                        permissions: List<String>,
                                        never: Boolean
                                    ) {
                                        if (never) {
                                            com.jsnkj.basic.util.ToastUtils.show("被永久拒绝授权，请手动授予存储权限")
                                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                            XXPermissions.startPermissionActivity(
                                                requireActivity(),
                                                permissions
                                            )
                                        } else {
                                            com.jsnkj.basic.util.ToastUtils.show("获取存储权限失败")
                                        }
                                    }
                                })
                        }
                    }
                })

            if (it.isNullOrEmpty()) {
                mVDB.txtError.visibility = View.VISIBLE
                mVDB.rvHome.visibility = View.GONE

            } else {
                mVDB.txtError.visibility = View.GONE

                mVDB.rvHome.apply {
                    layoutManager =
                        LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
                    adapter = homeAdapter
                    visibility = View.VISIBLE
                    isFocusable = false
                }
            }
        }


        mVM.errorResult.observe(this) {
            ErrorResultUtil.errorResult(requireActivity() as BaseMVVMActivity<*, *>, it)

            mVDB.txtError.visibility = View.VISIBLE
            mVDB.rvHome.visibility = View.GONE
        }

        mVM.postAppList()

        mVDB.txtItemAppName.text = requireActivity().getString(R.string.app_name)
        mVDB.txtItemAppName.setOnClickListener {
            if (com.jsnkj.basic.BuildConfig.DEBUG) {
                startActivity(requireActivity(), TextActivity::class.java)
            }
        }
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.img_home_join_player -> {
                val content = SharePreferencesUtil.getInstance().getSettingEntity().player_group_url
                if (content.isNullOrEmpty()) {
                    com.jsnkj.basic.util.ToastUtils.show("数据获取失败，请稍后再试")
                    return
                }
                if (joinPlayerDialog?.isShowing == true) {
                    joinPlayerDialog?.dismiss()
                }

                joinPlayerDialog = JoinPlayerDialog(requireActivity(), content,
                    object : JoinPlayerDialog.onItemClickListener {
                        override fun saveItemClick(bitmap: Bitmap?) {
                            if (null == bitmap) {
                                com.jsnkj.basic.util.ToastUtils.show("保存失败")
                                return
                            }
                            MediaUtil.savePuzzleBitmap(
                                requireActivity(), bitmap, SpConfig.IMG_SAVE_NAME
                            ) { state, _ ->
                                if (state) {
                                    bitmap.recycle()
                                    com.jsnkj.basic.util.ToastUtils.show("已成功保存到相册")
                                } else {
                                    com.jsnkj.basic.util.ToastUtils.show("保存失败，请重试")
                                }
                            }
                        }
                    })

                joinPlayerDialog?.show()
            }
        }
    }


    override fun onResume() {
        super.onResume()
        mVDB.tv2.requestFocus()
    }
}